<?php
namespace Cyfy\Modules\jquerySWFUpload;

/**
 * Jquery upload plugin - this class is server part for uploading.
 */

class Module extends \Cyfy\Module
{
    /**
     * Ajax callback
     */
	static function ajax($name)
	{
		switch($name)
		{
			case "deleteTemporaryFile":
				return self :: deleteTemporaryFile($_POST["filename"], $_POST["originalFilename"]);
		}
	}

    /**
     * File uploading - called by SWF.
     */
	static function call($name)
	{
		switch($name)
		{
			case "upload":
				return self :: fileUpload($_POST["customFilename"]);
		}
	}
	
    /**
     * Copies source file from tmp to dest.
     * Removes thumbnail, if exists.
     *
     * @param string Source file
     * @param string Destination
     * @return bool True if copy succesful.
     */
	static public function moveUploadedFile($source, $destination)
	{
		$r = copy('tmp/' . $source, $destination);
        \Cyfy\Cyfy ::  delete('tmp/resized_' . $source);
        \Cyfy\Cyfy ::  delete('tmp/' . $source);
        return $r;	
	}
	
    /** 
     * Creates a unique filename - if 2 files with same name.
     *
     * @param string File prefix
     * @param string Filename
     * @return string New filename
     */
	static private function getFilename($prefix, $file)
	{
		$i = 0;
		$p = "";
		while(file_exists('tmp/' . $prefix . $p . (($p != "") ? "_" : "") . $file))
		{
			$i++;
			$p = $i;
		}
		$file = $p . (($p != "") ? "_" : "") . $file;	
		return $file;
	}
	
    /**
     * Uploads a file and PRINTS NEW FILENAME FOR UPLOADED FILE.
     *
     * @param prefix File prefix
     */
	static private function fileUpload($prefix)
	{
		foreach($_FILES as $upload)
		{
			// file exists - upload as different
			$file = self :: getFilename($prefix, $upload["name"]);
			
			
			// do copy
			if(copy($upload["tmp_name"], 'tmp/' . $prefix . $file))
			{
				// new filename
				print $file;
                
                if(\Cyfy\Modules\Image\Image :: isImage($file)){
                    // resize
                    $i = new \Cyfy\Modules\Image\Image('tmp/' . $prefix . $file);
                    $i -> resize(100, 50);
                    $i -> saveAs('tmp/resized_' . $prefix . $file);
                    $i -> close();
                }
			}
			else
			{
				print "ERROR";
			}
		}
	}

    /**
     * Deletes a temoray file
     *
     * @param string Real filename
     * @param string Original name
     * @return bool
     */
	static private function deleteTemporaryFile($filename, $original)
	{
		if($filename){
			\Cyfy\Message :: set(self :: t(111, array($original)));
			\Cyfy\Cyfy ::  delete('tmp/resized_' . $filename);
			return \Cyfy\Cyfy ::  delete('tmp/' . $filename);
		}else{
			return false;
		}
	}
}